from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

# 1.获取数据
iris = load_iris()

# 2.数据基本处理
xTrain, xTest, yTrain, yTest = train_test_split(iris.data, iris.target, test_size=0.2, random_state=22)
# print("训练集特征值x_train=",x_train)
# print("测试集特征值x_train=",x_test)
# print("训练集目标值x_train=",y_train)
# print("测试集目标值x_train=",y_test)


# 3.特征工程 - 特征预处理
transfer = StandardScaler()
xTrain = transfer.fit_transform(xTrain)
xTest = transfer.transform(xTest)

# 4.机器学习 - KNN
# 4.1.实例化估算器
estimator = KNeighborsClassifier(n_neighbors=5)
# 4.2.模型训练
estimator.fit(xTrain, yTrain)

# 5.模型评估
yPre = estimator.predict(xTest)
# 5.1.预测值结果输出
print("预测值是", yPre)
print("预测值核真实值的对比", yPre == yTest)

# 5.2.准确率计算
score = estimator.score(xTest, yTest)
print("准确率=", score)
